//
//  LMShowViewController.m
//  舍品
//
//  Created by 楼 眉 on 16/2/19.
//  Copyright © 2016年 楼 眉. All rights reserved.
//
#pragma mark - 帖子列表控制器
#import "LMShowViewController.h"
#import <MJRefresh.h>
#import "LMTableViewCell.h"
#import "LMPost.h"
#import "LMPostFrame.h"
#import "LMMoreShowController.h"
//#import "LMShowPostMoreController.h"
#import <ReactiveCocoa.h>
#import <QBImagePickerController.h>
#import "LMReportController.h"
#import "LMWarningLabel.h"

static              NSInteger               const           KShowHeaderCount        =           1;
static              NSInteger               const           KShowFooterCount          =           4;


@interface LMShowViewController ()<QBImagePickerControllerDelegate>
@property (nonatomic,strong)  NSMutableArray *postFrames;
@property (nonatomic,weak)  UIImageView *tempView;
@property (nonatomic,strong) NSDate *FirstCreatedAt;
@property (nonatomic,strong)  NSDate *lastCreatedAt;
@end

@implementation LMShowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //关闭自动布局
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    //加入下拉刷新
    __weak typeof (self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
        if (manger.isReachable == NO) {
            [LMWarningLabel LM_createWarningLabelWithTitle:nil];
            [weakSelf.tableView.mj_header endRefreshing];
        }
        else
        {
            [weakSelf requestData];
        }
    }];
    
    [self.tableView.mj_header beginRefreshing];
    //解决tableview刷新数据前显示的自带cell
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    //加入上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if ([AFNetworkReachabilityManager sharedManager].isReachable == NO) {
            [weakSelf.tableView.mj_footer endRefreshing];
            [LMWarningLabel LM_createWarningLabelWithTitle:nil];
        }else
        {
        [weakSelf requestMoreData];
        }
    }];

    LMUser *user = [LMUser currentUser];
    NSString *title = user.nickname;
    self.navigationItem.title = title;
}
#pragma mark - 上拉刷新请求数据
- (void)requestMoreData
{
    NSMutableArray *tempFrames = [NSMutableArray array];
    AVQuery *query = [AVQuery queryWithClassName:@"post"];
    [query whereKey:@"classify" equalTo:@"s"];
    [query orderByDescending:@"createdAt"];
    [query whereKey:@"createdAt" lessThan:_lastCreatedAt];
    query.limit = KShowFooterCount;
    __weak typeof(self) weakSelf = self;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count == 0) {
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        else
        {
            LMPost *tempPost = objects.lastObject;
            _lastCreatedAt = tempPost.createdAt;
            for (LMPost *post in objects) {
                LMPostFrame *postFrame = [[LMPostFrame alloc]init];
                postFrame.post = post;
                [tempFrames addObject:postFrame];
            }
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.postFrames];
            [tempArray addObjectsFromArray:tempFrames];
            weakSelf.postFrames = tempArray;
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
        }
    }];

}
#pragma mark - 下拉刷新请求数据
- (void)requestData
{
    NSMutableArray *tempFrames = [NSMutableArray array];
    AVQuery *query = [AVQuery queryWithClassName:@"post"];
    [query whereKey:@"classify" equalTo:@"s"];
    [query orderByDescending:@"createdAt"];
    if (_FirstCreatedAt) {
        [query whereKey:@"createdAt" greaterThan:_FirstCreatedAt];
    }
    query.limit = KShowHeaderCount;
    __weak typeof(self) weakSelf = self;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count == 0) {
            [LMWarningLabel LM_createWarningLabelWithTitle:@"暂时没有更新的帖子"];
            [weakSelf.tableView.mj_header endRefreshing];
        }
        else
        {
            LMPost *firstPost = objects.firstObject;
            _FirstCreatedAt = firstPost.createdAt;
            LMPost *lastPost = objects.lastObject;
            _lastCreatedAt = lastPost.createdAt;
        for (LMPost *post in objects) {
            LMPostFrame *postFrame = [[LMPostFrame alloc]init];
            postFrame.post = post;
            [tempFrames addObject:postFrame];
        }
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:tempFrames];
        [tempArray addObjectsFromArray:self.postFrames];
        weakSelf.postFrames = tempArray;
        [weakSelf.tableView.mj_header endRefreshing ];
        [weakSelf.tableView reloadData];
        }
    }];
}

#pragma mark - TableView datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.postFrames.count;
}

- (LMTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    LMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[LMTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        __weak typeof(self) weakSelf = self;
        [[cell rac_signalForSelector:@selector(reportBtnClick)] subscribeNext:^(id x) {
            if (self.postFrames.count) {
                LMPostFrame *postFrame = weakSelf.postFrames[indexPath.row];
                [weakSelf reportBtnClick:postFrame.post];
            }
        }];
    }
    if (self.postFrames.count) {
        LMPostFrame *postFrame = self.postFrames[indexPath.row];
        cell.postFrame = postFrame;
        cell.height += 10;
}
  
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LMPostFrame *postFrame = self.postFrames[indexPath.row];
    return postFrame.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    LMPostFrame *lmPostFrame = self.postFrames[indexPath.row];
    NSString *postId = lmPostFrame.post.objectId;
//    LMMoreShowController *moreShowVc = [LMMoreShowController createWIthLMpost:lmPostFrame.post];
    LMMoreShowController *moreShowVc = [[LMMoreShowController alloc]init];
    moreShowVc.postFrame = lmPostFrame;
    moreShowVc.postId = postId;
    [self.navigationController pushViewController:moreShowVc animated:YES];
}

#pragma mark - 举报按钮被点击
- (void)reportBtnClick
{
}
- (void)reportBtnClick:(LMPost *)post
{
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
//        UIAlertAction *actionNan = [UIAlertAction actionWithTitle:@"收藏" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//        }];
//        [alertVc addAction:actionNan];
    
        UIAlertAction *actionNv = [UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"report" bundle:[NSBundle mainBundle]];
            LMReportController *reportVc = [storyboard instantiateViewControllerWithIdentifier:@"reportSB"];
            reportVc.post = post;
            [self.navigationController pushViewController:reportVc animated:YES];
        }];
        [alertVc addAction:actionNv];
    
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertVc addAction:actionCancel];
        
        [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark - waring
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - dealloc
- (void)dealloc
{
    NSLog(@"dealloc--showVc");
}
@end
